package dao.hibernate;


import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.DOMWriter;
import org.hibernate.MappingException;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import service.configuration.IConfiguration;


@Service
@Lazy(value=true)
public class HibernateUtilRef extends HibernateUtil {
	
	/* initialise le sessionFactory d'hibernate après avoir lu la configuration principale du fichier
	   hibernate.cfg.xml et avoir ajouté les mappings des entitités dynamiquement
	*/ 
	
	@Autowired
	public HibernateUtilRef(IConfiguration config) {
		super(config, "hibernate_ref.cfg.xml");
		
		try {
			// on ajoute les mappings : 
			addRefMappings();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		try {
			// on initialise la SessionFactory :
			sessionFactory = hibernateConfig.buildSessionFactory();
		} catch (Throwable ex) {
			System.err.println("Initial SessionFactory creation failed." + ex);
			throw new ExceptionInInitializerError(ex);
		}
	}
	
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}
	
	
	
	private void addRefMappings() throws MappingException, DocumentException {
		DOMWriter writer = new DOMWriter();
		
		Document personMapping = createHibernatePersonSheetMapping();
		hibernateConfig.addDocument(writer.write(personMapping));
		
		for(Document mapping : createHibernateSheetsMappings()) {
			hibernateConfig.addDocument(writer.write(mapping));
		}
	}

}
